﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;

public class KeyValuePair
{
    public string key;
    public string value;
}

public class ReadOnlyHtmlAttribute
{
    public ReadOnlyHtmlNode Belongs { get; private set; }
    public string Name { get; private set; }
    public string Value { get; private set; }

    public ReadOnlyHtmlAttribute(ReadOnlyHtmlNode belongs, string name, string value)
    {
        Belongs = belongs;
        Name = name;
        Value = value;
    }
}

public class ReadOnlyHtmlNode : ArrayTreeNodeProtected<ReadOnlyHtmlNode>
{

    public ReadOnlyCollection<ReadOnlyHtmlAttribute> Attributes { get; private set; }

    public ReadOnlyHtmlAttribute GetAttribute(string attributeName)
    {
        attributeName = attributeName.ToLower();
        for (int i = 0; i < Attributes.Count; i++)
        {
            if (Attributes[i].Name.ToLower() == attributeName)
            {
                return Attributes[i];
            }
        }
        return null;
    }

    public string Name { get; private set; }
    public string InnerText { get; private set; }

    public string Id { get; private set; }

    private ReadOnlyHtmlNode()
    {
    }

    public static ReadOnlyHtmlNode FromRawNodeRoot(RawNode raw_root)
    {
        return FromRawNode(raw_root, null);
    }

    static ReadOnlyHtmlNode FromRawNode(RawNode raw_node, ReadOnlyHtmlNode parent)
    {
        ReadOnlyHtmlNode node = new ReadOnlyHtmlNode();
        node.Parent = parent;
        node.InnerText = raw_node.InnerText ?? "";
        node.Name = raw_node.Name ?? "";

        node.Id = "";

        List<ReadOnlyHtmlAttribute> ats = new List<ReadOnlyHtmlAttribute>(raw_node.attributes.Count);
        for (int i = 0; i < raw_node.attributes.Count; i++)
        {
            ats.Add(new ReadOnlyHtmlAttribute(node, raw_node.attributes[i].key, raw_node.attributes[i].value));
            if (raw_node.attributes[i].key.ToLower() == "id")
            {
                node.Id = raw_node.attributes[i].value ?? "";
            }
        }

        node.Attributes = new ReadOnlyCollection<ReadOnlyHtmlAttribute>(ats);

        node.childs = new ReadOnlyHtmlNode[raw_node.ChildCount];
        for (int i = 0; i < raw_node.ChildCount; i++)
        {
            node.childs[i] = FromRawNode(raw_node.GetChild(i), node);
        }

        return node;

    }

}

public class RawNode : ListTreeNodepublic<RawNode>
{

    public string Name;

    public string InnerText;

    public List<KeyValuePair> attributes;

    public RawNode()
    {
        childs = new List<RawNode>();
        attributes = new List<KeyValuePair>();
    }

}